<?php
/**
 * Created by PhpStorm.
 * User: cdsile
 * Date: 2019/5/8
 * Time: 19:22
 */
function returnData($data=[],$message='success',$code=2000){
       $res =  [
         'status_code'=> $code,
         'message'=> $message,
         'data' => $data,
       ];

       return response($res,200);
}

/**
 * Notice:
 * Date: 2019/5/13
 * Time: 16:23
 * @author dongdong
 * @param $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int $root
 * @return array
 */
function list_tree_Intelligence($list, $pk='id', $pid = 'pid', $child = 'listArea', $root = 0) {
    //创建Tree
    $tree = array();
    if (is_array($list)) {
        //创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }

        $ids = array_map(function($item) use($pk){
            return $item[$pk];
        },$list);

        foreach ($list as $key => $data) {
            //判断是否存在parent
            $parantId = $data[$pid];

            if ($root == $parantId||!in_array($parantId, $ids)) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parantId])) {
                    $parent = &$refer[$parantId];
                    $parent[$child][] = &$list[$key];
                }
            }

        }
    }

    return $tree;
}




function arrToOne($multi,$deleteOrg=true) {
   foreach ($multi as $mk=>&$mv) {
       if (is_array($mv)) {
           foreach ($mv as $k=>$v) {
               if (is_array($v)) {
                   foreach ($v as $ik=>$item) {
                        if (isset($mv[$ik])) {
                            continue;
                        }
                       $mv[$ik] = $item;
                   }
                   if ($deleteOrg) {
                       unset($mv[$k]);
                   }
              }

           }
       }
   }
 return $multi;
}


function getChidldata ($list,$optionsParent=[],$index=0)
{
    $index += 2;
    $str = '&nbsp; &nbsp;&nbsp;&nbsp;';
    $nump = '';
    for ($i=0;$i<$index;$i++) {
        $nump .= $str;
    }
    foreach ($list as $key=>$val) {
        $optionsParent[$val['id']] = $nump.$val['name'];
        if (isset($val['child'])) {
            $optionsParent = getChidldata($val['child'],$optionsParent,$index);
        }
    }

    return $optionsParent;
}


if (!function_exists('msgReturn')) {
    /**
     * @param $data
     * @param null $to_uid 发给的client_id  或 uid
     * @param string $from_client_id 来自的client_id, 默认为系统
     * @param string $type  error,close
     * @param string $msg
     * @param bool $status   成功还是失败的 返回数据
     * @throws Exception
     */
    function msgReturn ($data, $to_uid = null, $from_uid = 'sys', $type = 'default', $msg = 'success', $status = true)
    {
        $res = [
            'sign' => 123482365,
            'type' => $type,
            'data' => $data,
            'status' => $status,
            'to' => $to_uid,
            'from' => $from_uid ,
            'msg' => $msg
        ];
        $jsonstr = json_encode($res);
        \Illuminate\Support\Facades\Log::stack(['socket'])->info($jsonstr);
        if (!$to_uid) {
            \GatewayClient\Gateway::sendToAll($jsonstr);
        } else {
            try{
                if($type == 'connect') {
                    \GatewayClient\Gateway::sendToClient($to_uid, $jsonstr);
                }else {
                    \GatewayClient\Gateway::sendToUid($to_uid, $jsonstr);
                }
            } catch (Exception $exception) {
                \Illuminate\Support\Facades\Log::stack(['scoket'])->error('msgReturn  scoket');
            }

        }
    }
}

if (!function_exists('msgByUid')) {
    /**
     * @param $data
     * @param null $to_uid
     * @param string $from_client_id
     * @param string $type  msginit=> 消息连接初始化
     * @param string $msg
     * @param bool $status
     * @throws Exception
     */
    function msgByUid ($data, $to_uid= null, $from_client_id = 'sys', $type = 'default', $msg = 'success', $status = true)
    {
        $res = [
            'sign' => 123482365,
            'type' => $type,
            'data' => $data,
            'status' => $status,
            'to' => $to_uid? 'all' : $to_uid,
            'from' => $from_client_id ,
            'msg' => $msg
        ];
        $jsonstr = json_encode($res);
        if (!$to_uid) {
            \GatewayClient\Gateway::sendToAll($jsonstr);
        } else {
            try{
                \GatewayClient\Gateway::sendToUid($to_uid, $jsonstr);
            } catch (Exception $exception) {
                \Illuminate\Support\Facades\Log::stack(['scoket'])->error('msgReturn  scoket');
            }

        }
    }
}

/**
 * socket 统一消息回复
 */
if (!function_exists('returnSocket')) {
    function returnSocket($type, $data) {
        $res = [
            'type' => $type,
            'data' => $data,
        ];
        return json_encode($res);
    }
}



#
function TimeDiff($end_time)
{
    $difftime = strtotime( $end_time) - strtotime('now');
    return  $difftime>0?$difftime:0;
}



# 生成 Code;
function makeCode($lenth=6) {
    $res = [];
    $codes = [
        1,2,3,4,5,6,7,8,9
    ];
    $stringCode = ['A','B','C','D','E',
        'F','G','H','I',
        'J','K','L','M','N',
        'O','P','Q','R','S','T','U','V','W','X','Y','Z'];

    $resarr = [];
    $data = array_rand($codes,$lenth);
    foreach ($data as $val)
    {
        $resarr[] =  $codes[$val] ;
    }
    return implode('',$resarr);
}


function staticUrl($url){
//    dd(config('view.static'));
    return config('view.static').'/'.$url;
}

function makeToken($user_id){
    $data = ['user_id'=>$user_id,'time'=>time()];
    $str = json_encode($data);
    $token = encrypt($str);
    return $token;
}

function makeNumber($pre=''){
    $number = $pre.date("YmdHis").rand(100,999);
    return $number;
}

## 获取限制数据；
function getArrayLimit($data,$number = 10)
{
    if (count($data)>10) {
        return array_slice($data,0,10);
    }
    return $data;
 }


/**
 * ojbectAssign 对象赋值；
 * @time:2020/2/5-11:39
 * @param $object 操作对象
 * @param array $data 操作数据 【‘name’=>value】
 * @param array $attributess ['name','id']
 *
 */
function ojbectAssign($object, array $data, $attributess = [] )
{
    if (empty($attributess)) {
        foreach ($data as $attribute=>$attributeVal)
        {
            $object->$attribute = $attributeVal;
        }
    }

    else {
        foreach ($data as $attribute => $attributeVal)
        {
            foreach ($attributess as $attributeItem) {
                if ($attributeItem ==  $attribute)  {
                    $object->$attributeItem = $attributeVal;
                }
            }
        }
    }

    return $object;
}

/**
 * distance  经纬度 2点之间的距离；
 * @time:2020/2/6-9:11
 * @param $lat1
 * @param $lon1
 * @param $lat2
 * @param $lon2
 * @author:dongdong
 * @return float
 */
function distance($lat1, $lon1, $lat2, $lon2) {
    $R = 6371393; //地球平均半径,单位米
    $dlat = deg2rad($lat2-$lat1); # deg2rad() 函数将角度转换为弧度。
    $dlon = deg2rad($lon2-$lon1);
    $a = pow(sin($dlat/2), 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * pow(sin($dlon/2), 2);
    $c = 2 * atan2(sqrt($a), sqrt(1-$a));
    $d = $R * $c;
    return round($d);
}

/**
 * currentTimestamp 当前时间
 * @time:2020/2/6-10:41
 * @author:dongdong
 * @return false|string
 */
function currentTimestamp()
{
    return date("Y-m-d H:i:s");
}


/**
 * getLastName  获取最后的name
 * @time:2020/2/10-15:36
 * @author:dongdong
 * @queryParam example_id required The id of the location.
 * @bodyParam example_id required The id of the location.
 * @response {
 * "data": {
 * },
 * "status_code": 200,
 * "message" : "success"
 * }
 */
function getLastName($class)
{
    $class = get_class($class);
    if($class) {
        $arr = explode('\\',$class);
        if (is_array($arr)) {
            return end($arr);
        }
        return $class;
    }
    return $class;
}

# 设置 后台  select 语言；
function adminLoadSelect2LangJs($lang='zh-CN'){
    \Encore\Admin\Admin::js("/vendor/laravel-admin/AdminLTE/plugins/select2/i18n/{$lang}.js");
}


function ddtt(\Illuminate\Foundation\Testing\TestResponse $response){
    $str = $response->getContent();
    $arr = json_decode($str,true);
    if (is_array($arr)) {
        dd($arr);
    }
    dd($str);
}


/**
 * getAdminEditId  后台获取更新的id
 * @time:2020/4/6-20:35
 * laravel-admin  表单编辑 的主键；
 * @author:dongdong
 * @response {
 * "data": {
 * },
 * "status_code": 200,
 * "message" : "success"
 * }
 * @return int
 */
function getAdminEditId(){
    $path = \request()->getPathInfo();
    $itemArr = explode('/',$path);
    $urlarr = [];
    foreach ($itemArr as $k=>$val) {
        if ($val) {
            $urlarr[] = $val;
        }
    }
    $key  = 0;
    if (count($urlarr) >=3 ){
        if ( isset($urlarr[3]) && is_numeric($urlarr[3]) ) {
            $key = $urlarr[3];
        }
    }
    return $key;
}


function urloss($filename,array $param=[]){
   $url = \App\Service\Aliyunoss::instance()->signedUrl($filename,$param);
   if ($url) {
       return $url;
   }
   return '';
}


